<template>
	<view class="intro-page">
		<!-- 文字介绍部分 -->
		<view class="section">
			<textarea class="intro-textarea" v-model="introText" placeholder="我，阳光，随意，勤勉，又有完美的生活目标，生活在这个世界上。你，只求如同一阵清新的空气，让我呼吸中，融为一体" maxlength="2000"></textarea>
			<view class="word-count">
				<text>已输入{{ introText.length }}/2000个字符</text>
			</view>
			<view class="tips">
				<text class="tips-text">不知道怎么写？从模板中选择 ></text>
			</view>
		</view>
		
		<!-- 语音介绍部分 -->
		<view class="section">
			<view class="section-title">语音介绍</view>
			<view class="voice-recorder" @click="recordVoice">
				<image class="mic-icon" src="/static/icons/mic.png" mode="aspectFit"></image>
				<text class="record-text">按住开始录音</text>
			</view>
			<view class="tips">
				<text class="tips-hint">可以高歌一曲/一本正经的自我介绍/温情喊话..</text>
			</view>
		</view>
		
		<!-- 性格标签部分 -->
		<view class="section">
			<view class="section-title">我的性格</view>
			<view class="tags-container">
				<view class="tag-item" v-for="(tag, index) in personalityTags" :key="index" :class="{ active: selectedPersonalityTags.includes(tag) }" @click="togglePersonalityTag(tag)">
					<text>{{ tag }}</text>
				</view>
			</view>
		</view>
		
		<!-- 爱好标签部分 -->
		<view class="section">
			<view class="section-title">我的爱好</view>
			<view class="tags-container">
				<view class="tag-item" v-for="(tag, index) in hobbyTags" :key="index" :class="{ active: selectedHobbyTags.includes(tag) }" @click="toggleHobbyTag(tag)">
					<text>{{ tag }}</text>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-btn" @click="saveIntro">
			<text>完成</text>
		</view>
	</view>
</template>

<script>
	import { getUserIntroApi, updateUserIntroApi } from '@/api/index.js';
	import { mapState } from 'vuex';
	
	export default {
		data() {
			return {
				introText: '',
				voiceUrl: '',
				personalityTags: ['浪漫迷人', '成熟稳重', '风趣幽默', '乐天达观', '活泼可爱', '忠厚老实', '淳朴善良', '温柔体贴', '多愁善感', '新潮时尚', '热辣动感', '豪放不羁'],
				selectedPersonalityTags: [],
				hobbyTags: ['音乐', '影视', '数码', '汽车', '时尚', '旅游', '美食', '文学'],
				selectedHobbyTags: [],
				isRecording: false
			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		onLoad() {
			this.getUserIntro();
		},
		methods: {
			// 获取用户自我介绍
			getUserIntro() {
				if (!this.userInfo || !this.userInfo.id) {
					this.$hr.methods.toast('请先登录');
					setTimeout(() => {
						this.$hr.methods.goPage('/login/index');
					}, 1500);
					return;
				}
				
				this.$hr.methods.loading();
				getUserIntroApi().then(res => {
					this.$hr.methods.hideloading();
					if (res) {
						this.introText = res.intro_text || '';
						this.voiceUrl = res.voice_url || '';
						this.selectedPersonalityTags = res.personality_tags || [];
						this.selectedHobbyTags = res.hobby_tags || [];
					}
				}).catch(() => {
					this.$hr.methods.hideloading();
					this.$hr.methods.toast('获取自我介绍失败');
				});
			},
			
			// 切换性格标签
			togglePersonalityTag(tag) {
				const index = this.selectedPersonalityTags.indexOf(tag);
				if (index === -1) {
					// 最多选择5个标签
					if (this.selectedPersonalityTags.length >= 5) {
						this.$hr.methods.toast('最多选择5个性格标签');
						return;
					}
					this.selectedPersonalityTags.push(tag);
				} else {
					this.selectedPersonalityTags.splice(index, 1);
				}
			},
			
			// 切换爱好标签
			toggleHobbyTag(tag) {
				const index = this.selectedHobbyTags.indexOf(tag);
				if (index === -1) {
					// 最多选择5个标签
					if (this.selectedHobbyTags.length >= 5) {
						this.$hr.methods.toast('最多选择5个爱好标签');
						return;
					}
					this.selectedHobbyTags.push(tag);
				} else {
					this.selectedHobbyTags.splice(index, 1);
				}
			},
			
			// 录制语音
			recordVoice() {
				// 检查是否正在录音
				if (this.isRecording) {
					return;
				}
				
				// 开始录音
				this.isRecording = true;
				const recorderManager = uni.getRecorderManager();
				
				recorderManager.onStart(() => {
					this.$hr.methods.toast('开始录音，请讲话...');
				});
				
				recorderManager.onStop((res) => {
					this.isRecording = false;
					const { tempFilePath } = res;
					
					// 上传语音文件
					this.$hr.methods.loading('上传中...');
					uni.uploadFile({
						url: this.$hr.config.SERVER_URL + '/api/users/v1/voice',
						filePath: tempFilePath,
						name: 'voice',
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('token')
						},
						success: (uploadRes) => {
							this.$hr.methods.hideloading();
							const data = JSON.parse(uploadRes.data);
							if (data.code === 200) {
								this.$hr.methods.toast('语音上传成功', 'success');
								this.voiceUrl = data.data.voice_url;
							} else {
								this.$hr.methods.toast(data.message || '上传失败');
							}
						},
						fail: () => {
							this.$hr.methods.hideloading();
							this.$hr.methods.toast('上传失败');
						}
					});
				});
				
				recorderManager.onError((err) => {
					this.isRecording = false;
					this.$hr.methods.toast('录音失败: ' + err.errMsg);
				});
				
				// 开始录音
				recorderManager.start({
					duration: 60000, // 最长录音时间，单位ms
					sampleRate: 44100,
					numberOfChannels: 1,
					encodeBitRate: 192000,
					format: 'mp3'
				});
				
				// 监听触摸结束事件，停止录音
				uni.onTouchEnd(() => {
					if (this.isRecording) {
						recorderManager.stop();
					}
				});
			},
			
			// 保存自我介绍
			saveIntro() {
				if (!this.introText.trim()) {
					this.$hr.methods.toast('请输入自我介绍');
					return;
				}
				
				this.$hr.methods.loading('保存中...');
				updateUserIntroApi({
					intro_text: this.introText,
					voice_url: this.voiceUrl,
					personality_tags: this.selectedPersonalityTags,
					hobby_tags: this.selectedHobbyTags
				}).then(res => {
					this.$hr.methods.hideloading();
					this.$hr.methods.toast('保存成功', 'success');
					
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}).catch(() => {
					this.$hr.methods.hideloading();
					this.$hr.methods.toast('保存失败');
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style> 